<?php

namespace App\Models;

use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;

/**
 * 积分商城商品模型
 * Class Goods
 */
class Goods extends BaseModel
{

    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'goods';

    /**
     * 关联商品类型
     */
    public function conType()
    {
        return $this->hasOne(GoodsType::class, 'id', 'type_id');
    }

    /**
     * 关联创建管理员
     */
    public function conManage()
    {
        return $this->hasOne(Manage::class, 'id', 'manage_id');
    }

    /**
     * 关联商品图片
     */
    public function conImg()
    {
        return $this->hasMany(GoodsImg::class, 'goods_id', 'id');
    }


    /**
     * 获取最新商品列表
     */
    public function lists($type_id = null, $user_id = null, $keywords = null, $limit = 10)
    {
        $time = date("Y-m-d H:i:s");
        $res = $this->from('goods as g')->select('g.id', 'g.name', 'g.img', 'g.score', 'price', 'number', 'has_number', 'start_time', 'end_time', 'times', 'send_way')
            ->where(function ($query) use ($type_id) {
                if (!empty($type_id)) {
                    $query->where('g.type_id', $type_id);
                }
            })
            ->where(function ($query) use ($keywords) {
                if (!empty($keywords)) {
                    $query->where('g.name', 'like', "%$keywords%");
                }
            })
            ->join('goods_type as t', 'g.type_id', '=', 't.id')
            ->where('g.is_del', 1)
            ->where('t.is_del', 1)
            // ->where('start_time','<=', $time)
            //  ->where('end_time','>=',$time)//兑换时间已过的也可以显示
            ->where('g.is_play', 1)
            ->orderByDesc('g.end_time')
            ->paginate($limit)
            ->toArray();

        if ($res['data']) {
            $orderModel = new GoodsOrder();
            foreach ($res['data'] as $key => $val) {
                $res['data'][$key]['surplus_number'] = $val['number'] - $val['has_number'];
                //是否可以兑换
                if ($res['data'][$key]['surplus_number'] <= 0) {
                    $res['data'][$key]['is_convert'] = false; //是否可以继续兑换
                } elseif ($val['start_time'] > date('Y-m-d H:i:s') ||  $val['end_time'] < date('Y-m-d H:i:s')) {
                    $res['data'][$key]['is_convert'] = false;
                } else {
                    if (!empty($user_id)) {
                        $times = $orderModel->getConversionNumber($user_id, $val['id']);
                        $res['data'][$key]['user_times'] = $times;
                        $res['data'][$key]['is_convert'] = $val['times'] === 0 || ($val['times'] - $times > 0) ? true : false;
                    } else {
                        $res['data'][$key]['is_convert'] = true;
                    }
                }
            }

            return $res;
        }
        return false;
    }
}
